import axios from "axios"
import type { InternalAxiosRequestConfig, AxiosResponse } from "axios"
import { useLoginStore } from "@/store/loginStore"
import { ElMessage } from "element-plus"

interface ResultDTO {
  status: number
  msg: string
  isSuccess: boolean
  data: any
}

enum HTTP_STATUS {
  AUTHENTICATION_FAILED = 40101, //登录验证失败
  LOGIN_EXPIRED = 40102, //登录已过期
  ACCESS_DENIED = 40301, //没有权限访问
  LOGIN_FAILED_INCORRECT_PASSWORD = 40302, //账号或密码错误
  USERNAME_NOTFOUND = 40401, //用户名未找到
  USERNAME_EXISTED = 40901, //用户名已经存在
  RESOURCE_EXISTED = 40902, //目标资源已经存在(冲突)
  USER_HAS_LOGIN = 40903, //用户已经登录
  UNKNOWN_SERVER_ERROR = 500 //服务器发生未知异常
}

const service = axios.create({
  baseURL: "/api",
  timeout: 10000000,
  withCredentials: false
})

service.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
  const loginStore = useLoginStore()
  if (loginStore.isAuthenticated()) {
    config.headers.Authorization = "Bearer " + loginStore.$state.token
  }
  config.headers["no-cookie"] = true
  return config
})

service.interceptors.response.use(
  (res: AxiosResponse<any>) => {
    const loginStore = useLoginStore()
    if (
      res.data.status === HTTP_STATUS.LOGIN_EXPIRED ||
      (res.data.status === HTTP_STATUS.AUTHENTICATION_FAILED && loginStore.isAuthenticated())
    ) {
      loginStore.removeToken()
    } else if(res.data.status === HTTP_STATUS.ACCESS_DENIED) {
      ElMessage.error(res.data.msg)
    }
    return res.data
  },
  (error) => {
    console.error("接收响应时发生错误: ")
    return Promise.reject(error.message)
  }
)

export default service
